<?php
/*
*	Kleophatra - Open Source Content Management System
*	------------------------------------------------------------------------
*	Copyright (C) 2007-2010, Sergio Milardovich <smilardovich@yahoo.com.ar>
*	This program is Free Software.
*
*	@package	Kleophatra
*	@subpackage	/lib
*	@license	http://www.gnu.org/copyleft/gpl.html GNU/GPL License 2.0
*	@author		Sergio Milardovich <smilardovich@yahoo.com.ar>
*	@link		http://www.kleophatra.org
*/
	require_once KLEO_CONFIG_DIR.'db/'.KLEO_DB_DRIVER.'.php';

	class kleocore extends kleodb{
		/*
	 	 * Sections array
	 	 * You can add/delete/modify sections from this array	
	 	 * Default values: 1=blog,2=gallery,3=downloads,4=files
	 	 */

		var $sections = array("","blog","gallery","downloads","files"); //Deprecated since 0.1

		function array_group($array){
			foreach($array as $a){
				//Case sensitive
				if(!$b[$a] or !$b[strtolower($a)]){
					$b[$a];
					$c[] = $a;
				}
				return $c;
			}
		}
		function get_core_value($valuename, $type='name', $ref=null){
			if(!empty($ref)){
				$extended_query = 'AND reference = '.$ref;
			} else {
				$extended_query = null;
			}
			switch($type){
				case "name":
					$query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."conf WHERE name = '$valuename' $extended_query LIMIT 1");
				break;
				case "id":
					if(is_numeric($type)){
						$this->apperror("get_core_value error: id must be numeric", "common");
					}
					$query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."conf WHERE cid = $valuename $extended_query LIMIT 1");
				break;
			}
			if($this->num_rows($query) !== 0){
				$row = $this->fetch_array($query);
				return $row['value'];
			} else {
				return false;
			}
			
		}

		function set_core_value($valuename, $replace, $ref=null, $id=null, $status=null, $cref=null){
			$set;
			$extends;
			if(!is_null($ref)){
				$extends .= 'AND `reference` = '.$ref.' ';
			}
			if(!is_null($id)){
				$extends .= 'AND `cid` = '.$id.' ';
			}
			if(!is_null($status)){
				$set .= ', `status` = '.$status.' ';
			}
			if(!is_null($cref)){
				$set .= ', `reference` = '.$cref.' ';
			}
			$this->query(" UPDATE `".KLEO_TABLE_PREFIX."conf` SET `value` = '$replace' $set WHERE `name` = '$valuename' $extends");
		}
		function add_core_value($name,$value,$reference=null,$type=1,$status=1){
			if($reference){
				$extended_query = 'AND reference = '.$reference;
			} else {
				$extended_query = NULL;
			}
			$query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."conf WHERE name = '$name' AND type = $type $extended_query LIMIT 1");
			if($this->num_rows($query) == 0){
				// Everything's in its right place.
				$this->query("INSERT INTO `".KLEO_TABLE_PREFIX."conf` (`cid` ,`name` ,`value` ,`reference` ,`type` ,`status`) VALUES (NULL ,'$name', '$value', '$reference', '$type', '$status');");
			} else {
				//Duplicated entry
				return false;
			}
		}
		function cleandate($date){
			$date = str_replace("-", "", $date);
			$date = str_replace(":", "", $date);
			$date = str_replace(" ", "", $date);
			return $date;
		}
		
		function get_the_tags($id,$links=true){
			$tags_query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."assoc WHERE assoctype = 4 AND associtem = $id");
			if($this->num_rows($tags_query)){
				while($tags_row = $this->fetch_array($tags_query)){
					$id = $tags_row['assoctopic'];
					$tag = $this->get_tag($id);
					if(!empty($tag['tagname'])){
						if($links == true){
							$tags[] = '<a href="index.php?module=search&q='.$tag['tagname'].'">'.$tag['tagname'].'</a>';
						} else {
							$tags[] = $tag['tagname'];
						}
					}
				}
				return implode(",",$tags);
			} else {
				return false;
			}
		}
		function all_the_damn_tags(){
			$tags_query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."assoc WHERE assoctype = 4");
			while($tags_row = $this->fetch_array($tags_query)){
				$tag = $this->get_tag($tags_row['assoctopic']);
				$tags[] = $tag['tagname'];
			}
			return implode(",",$tags);
		}

		function get_topic($arg){
			$query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."topics WHERE topicid = '$arg' or tname = '$arg'");
			$row = $this->fetch_array($query);
			return $row;
		}

		function get_tag($arg){
			$query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."tags WHERE tagid = '$arg' or tagname = '$arg'");
			$row = $this->fetch_array($query);
			return $row;
		}

		function get_the_topics($id,$type){
			$query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."assoc WHERE associtem = $id AND assoctype = '$type'");
			while($row = $this->fetch_array($query)){
				$topic = $this->get_topic($row['assoctopic']);
				if(!empty($topic['tname'])){
					$topics[] = '<a href="index.php?module=blog&cat='.$row['assoctopic'].'">'.$topic['tname'].'</a>';
				}
			}
			if(!empty($topics)){
				return implode(",",$topics);
			} else {
				return '('.L_NONE.')';
			}
		}
		function get_date(){
			return date("Y-m-d H:i:s");
		}
		function get_sections(){
			$sections = opendir(KLEO_MODULES_DIR);
			while (false !== ($section = readdir($sections))) {
				if($section !== '..' && $section !== '.'){
					$buff[] = $section;
				}
			}
			return $buff;
      		}
		function is_value($valuename,$ref=null){

			if(!empty($ref)){
				$extended_query = 'AND reference = '.$ref;
			} else {
				$extended_query = null;
			}
			$query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."conf WHERE name = '$valuename' $extended_query");
			if($this->num_rows($query) > 0){	
				return true;
			} else {
				return false;
			}
		}
		function apperror($content, $type='common'){
			// $type could be: 404, common, etc...
			switch($type){
				case 'common':
				$this->apploadlib(KLEO_LIB_DIR.'template.lib.php', "kleotemplate", $template);
				$template->tpl_load(KLEO_TEMPLATE_DIR.KLEO_CURRENT_TEMPLATE.'/tpl/errors/'.$type.'.tpl', $buff);
				$template->tpl_set("KLEO_ERROR", $content, $buff, $buff);
				$template->tpl_set("GO_BACK", $_SERVER['HTTP_REFERER'], $buff, $buff);
				$template->compile($buff,$buff);
				break;
				case 'pass':
				$this->apploadlib(KLEO_LIB_DIR.'template.lib.php', "kleotemplate", $template);
				$template->tpl_load(KLEO_TEMPLATE_DIR.KLEO_CURRENT_TEMPLATE.'/tpl/errors/insert_pass.tpl', $buff);
				$template->tpl_set("PID", $_SESSION['insert_pass'], $buff, $buff);
				$template->tpl_set("KLEO_ERROR", $content, $buff, $buff);
				$template->compile($buff,$buff);
				break;
			}

 			die($buff);

		}

		function apploadlib($file, $name, &$usename){

			if(file_exists($file)){
				require_once $file;
				$usename = new $name();
			} else if(file_exists(KLEO_SOURCE_DIR.$file)){
				require_once KLEO_SOURCE_DIR.$file;
				$usename = new $name();
			} else if(file_exists(KLEO_LIB_DIR.$file)){
				require_once KLEO_LIB_DIR.$file;
				$usename = new $name();
			}

		}

		function appclean(){
		
			unset($_SESSION);
			unset($_POST);
			unset($_COOKIE);
			$this->appreload();

		}

		function appredirect($location){
			header("Location: $location");
		}

		function appreload(){
			$location = $_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
			header("Location: $location");
		}

		function is_email($email){
			if(preg_match("/^[a-zA-Z0-9\.\-\_]*@[a-zA-Z0-9\.\-\_]*$/", $email, $matches)){
				return true;
			} else {
				return false;
			}
		}

		function is_web($web){
			if(preg_match("/^(?:http:\/\/)?((?:[\w\-]+(?:\.[\w^_]+)+){1}\S*)$/", $web, $matches)){
				return true;
			} else {
				return false;
			}
		}
		function is_image($image){
			if(getimagesize($image) == null){
				return true;
			} else {
				return false;
			}
		}
		function upload_file($source, $destination){


			if(file_exists($destination)){
				$this->apperror("The destination file already exists", "common");
			}

			move_uploaded_file($source, $destination);

		}

		function list_dir_files($dir){
			$dirs = array();
			if(is_dir($dir)){
				$dir = opendir($dir);
			}
			while ($direc = readdir($dir))
			if($direc !== '.' or $direc !== '..'){
  				array_push($dirs, $direc);
			}
			return $dirs;
		}
		function add_basic_tpl($name,$value){
			return $GLOBALS['basic_tpl'][] = array($name => $value);
		}

		/*
		 * kleophatra.org's services
		 */ 
		function get_latest_version(){
			if(!defined(KLEO_LOCAL_MODE)){
				if(!isset($_SESSION['latest_version'])){
					$_SESSION['latest_version'] = file_get_contents('http://kleophatra.org/services/info.php?v');
				}
				return $_SESSION['latest_version'];
			} else {
				return false;
			}
		}

		function get_latest_codename(){
			if(!defined(KLEO_LOCAL_MODE)){
				if(!isset($_SESSION['codename'])){
					$_SESSION['codename'] = file_get_contents('http://kleophatra.org/services/info.php?c');
				}
				return $_SESSION['codename'];
			} else {
				return false;
			}
		}
		
		function get_authors(){
			if(!defined(KLEO_LOCAL_MODE)){
				if(!isset($_SESSION['authors'])){
					$_SESSION['authors'] = file_get_contents('http://kleophatra.org/services/info.php?a');
				}
				return $_SESSION['authors'];
			} else {
				return false;
			}
		}

		function get_web_announces(){
			if(!defined(KLEO_LOCAL_MODE)){
				if(!isset($_SESSION['web_announces'])){
					$_SESSION['web_announces'] = file_get_contents("http://kleophatra.org/services/announce.txt");
				}
				return $_SESSION['web_announces'];
			} else {
				return false;
			}
		}

		/*
		 * This piece of code is based on Gekko CMS Network class
		 * The development of Gekko CMS has stopped on 2007/2008
		 * Anyway, you can get the code of the network class here:
		 * http://gekkoware.svn.sourceforge.net/viewvc/gekkoware/dist/src/lib/network.lib.php?view=log
		 */
		function sendmail($to, $subject, $message, $content_type = "text/plain", $headers = null,$from = null) {

			// preventing possible spam attacks
			$to = trim(preg_replace("/[\r|\n](.*?)/", "", $to));
			$subject = trim(preg_replace("/[\r|\n](.*?)/", "", $subject));
			$message = trim(preg_replace("/[\r|\n]\.[\r|\n](.*?)/", "", $message));
	

			if (!$headers)
				$headers = "";

			$headers .= "Mime-Version: 1.0\r\n";
			$headers .= "Content-Type: $content_type\r\n";
			if(empty($from)){
				$headers .= "From: ".$this->get_core_value('web_name')." <".$this->get_core_value('admin_email').">\r\n";
			} else {
				$headers .= "From: ".$from."\r\n";
			}
			$headers .= "Date: ".date("r")."\r\n";

			mail($to, $subject, $message, trim($headers));
 		}

		function is_topic($arg){
			$check_query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."topics WHERE tname = '$arg' OR topicid = '$arg'");
			if($this->num_rows($check_query) !== 0){
				return true;
			} else {
				return false;
			}
		}

		function is_tag($arg){
			$check_query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."tags WHERE tagname = '$arg' OR tagid = '$arg'");
			if($this->num_rows($check_query) !== 0){
				return true;
			} else {
				return false;
			}
		}
		function add_tag($name,$rank=0,$type=1,$status=1){
			$this->query("INSERT INTO `".KLEO_TABLE_PREFIX."tags` (
				`tagid` ,
				`tagname` ,
				`rank` ,
				`type` ,
				`status`
			) VALUES (
				NULL , '$name', '$rank', '$type', '$status'
			);");
		}


		function add_topic($name,$parent=0,$status=1,$desc=null,$group=null,$icon=null){

			$this->query("INSERT INTO `".KLEO_TABLE_PREFIX."topics` (
					`topicid`, 
					`tname`, 
					`tdesc`, 
					`ticon`, 
					`tparent`, 
					`tgroup`, 
					`tstatus`, 
					`date_created`
				) VALUES (
					NULL, '$name', '$desc', '$icon', '$parent', '$group', '$status', CURRENT_TIMESTAMP);
				");

		}
		function add_topic_group($name,$desc,$status=1){
			$this->query("INSERT INTO `".KLEO_TABLE_PREFIX."topics_groups` (
				`groupid` ,
				`gname` ,
				`gdesc` ,
				`gstatus` ,
				`date_created`
			) VALUES (
				NULL , '$name', '$desc', '', CURRENT_TIMESTAMP
			)");
		}
		function add_group($name,$section){
			$this->query("INSERT INTO `".KLEO_TABLE_PREFIX."groups` (
				`gid` ,
				`name` ,
				`sections`
			) VALUES (
				NULL , '$name', '$section'
			);");
		}
		function edit_group($id,$name){
			$this->query("UPDATE `".KLEO_TABLE_PREFIX."groups` SET `name` = '$name' WHERE `gid` = $id");
			$sections = $this->get_posted_sections();
			$this->query("UPDATE `".KLEO_TABLE_PREFIX."groups` SET `sections` = '$sections' WHERE `gid` = $id");
		}
		function set_topic($topic,$args){
			if(is_array($args)){
				foreach($args as $name => $value){
					$this->query("UPDATE `".KLEO_TABLE_PREFIX."topics` SET `$name` = '$value' WHERE `topicid` = $topic OR `tname` = '$topic' LIMIT 1");
				}
			} else {
					$this->query("UPDATE `".KLEO_TABLE_PREFIX."topics` SET `tname` = '$args' WHERE `topicid` = $topic OR `tname` = '$topic' LIMIT 1");
			}
		}
		function set_topics_group($group,$args){
			if(is_array($args)){
				foreach($args as $name => $value){
					$this->query("UPDATE `".KLEO_TABLE_PREFIX."topics_groups` SET `$name` = '$value' WHERE `groupid` = $group OR `gname` = '$group' LIMIT 1");
				}
			} else {
					$this->query("UPDATE `".KLEO_TABLE_PREFIX."topics_groups` SET `gname` = '$args' WHERE `groupid` = $topic OR `gname` = '$group' LIMIT 1");
			}
		}
		function add_assoc($topic,$item,$type){
			$this->query("INSERT INTO `".KLEO_TABLE_PREFIX."assoc` (
				`associd` ,
				`assoctopic` ,
				`associtem` ,
				`assoctype`
			) VALUES (
				NULL , $topic, $item, $type
			);");
		}
		function is_assoc($topic,$item,$type=1){
			$query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."assoc WHERE assoctopic = $topic AND associtem = $item AND assoctype = $type");
			if($this->num_rows($query) !== 0){
				return true;
			} else {
				return false;
			}
		}
		function is_remote_file($file_name) {
			return strpos($file_name, '://') && preg_match("#\.[a-zA-Z0-9]{1,4}$#", $file_name) ? true : false;
		}

		function is_home(){
			if(!isset($_GET['module']) or $_GET['module'] == KLEO_DEFAULT_MODULE){
				$return = true;
				foreach($_GET as $name => $value){
					if($name !== 'module' or $value !== KLEO_DEFAULT_MODULE){
						$return = false;
					}
				}
			}
			return $return;
		}
		function get_last_id(){
			$query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."blog ORDER BY id DESC LIMIT 1");
			$row = $this->fetch_array($query);
			return (int)$row['id']+1;
    		}
		function get_last_topic_id(){
			$query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."topics ORDER BY topicid DESC LIMIT 1");
			$row = $this->fetch_array($query);
			return (int)$row['topicid']+1;
    		}
		function get_last_topic_groups_id(){
			$query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."topics_groups ORDER BY groupid DESC LIMIT 1");
			$row = $this->fetch_array($query);
			return (int)$row['groupid']+1;
    		}
		function get_last_user_id(){
			$query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."users ORDER BY uid DESC LIMIT 1");
			$row = $this->fetch_array($query);
			return (int)$row['uid']+1;
    		}
		function get_last_widget_id(){
			$query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."widgets ORDER BY wid DESC LIMIT 1");
			$row = $this->fetch_array($query);
			return (int)$row['wid']+1;
    		}
		function get_last_menu_id(){
			$query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."menus ORDER BY mid DESC LIMIT 1");
			$row = $this->fetch_array($query);
			return (int)$row['mid']+1;
    		}
		function get_last_menu_items_id(){
			$query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."menus_items ORDER BY mitid DESC LIMIT 1");
			$row = $this->fetch_array($query);
			return (int)$row['mitid']+1;
		}
		function get_topics_select(){
			$query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."topics ORDER BY tname ASC");
			$topics['('.L_NONE.')'] = 0;
			while($row = $this->fetch_array($query)){
				$topics[$row['tname']] = $row['topicid'];
			}
			return $topics;
		}
		function copy_dir($src,$dst) {
			$dir = opendir($src);
			@mkdir($dst);
			while(false !== ( $file = readdir($dir)) ) {
				if (( $file != '.' ) && ( $file != '..' )) {
					if ( is_dir($src . '/' . $file) ) {
						$this->copy_dir($src . '/' . $file,$dst . '/' . $file);
					} else {
						copy($src . '/' . $file,$dst . '/' . $file);
					}
				}
			}
			closedir($dir);
		}
		function delete_group($id){
			$this->query("DELETE FROM `".KLEO_TABLE_PREFIX."groups` WHERE `gid` = $id LIMIT 1");
		}
		function delete_directory($dirname) {
			if (is_dir($dirname))
				$dir_handle = opendir($dirname);
			if (!$dir_handle)
				return false;
			while($file = readdir($dir_handle)) {
				if ($file != "." && $file != "..") {
					if (!is_dir($dirname."/".$file))
						unlink($dirname."/".$file);
         				else
            					$this->delete_directory($dirname.'/'.$file);    
      				}
   			}
   			closedir($dir_handle);
   			rmdir($dirname);
   			return true;
		}

		function the_date($format,$date=null){
			if(preg_match("/D/", $format, $matches)){
				$day = date('D', strtotime($date));
			}
			if(empty($date)){
				$date = $this->get_date();
			}
			return date($format, strtotime($date));
		}
		function get_posted_sections(){
			if(!isset($_POST['sections_all'])){
				foreach($_POST as $name => $value){
					if(substr($name,0,8) == 'section_'){
						$sections[] = $value;
						unset($name);
					}
				}
				return implode(",",$sections);
			} else {
				return '*';
			}
    		}
		function sanitize_string($string){
			return htmlentities(str_replace($string, " ","_"));
		}
		/*
		 * Convert a timestamp into an array
		 * this function is used, for example to generate RSS dates from the timestamps of the database
		 */
		function stamp2array($stamp){
			$output['y'] = substr($stamp,0,4);
			$output['m'] = substr($stamp,5,2);
			$output['d'] = substr($stamp,8,2);
			$output['h'] = substr($stamp,11,2);
			$output['i'] = substr($stamp,14,2);
			$output['s'] = substr($stamp,17,2);
			return $output;
		}
		/*
		 * Just a function to debug some warns in the development mode
		 */
		function sanitize_vars($vars){
			foreach($vars as $var){ 
				if(eval("isset($var);") == false){
					eval("$var = true;");
					eval("global $var;");
				}
			}
		}
	}
?>
